package com.dongpu.springboot.rabbitmq.original;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author biyuyang
 *
 * Java原生类支持RabbitMQ,直接运行主方法即可
 *
 */
public class ConfirmSender1 {

	private final static String QUEUE_NAME = "confirm";

	public static void main(String[] args)
		throws IOException, TimeoutException, InterruptedException {

		//1.创建连接到rabbitMQ的连接工厂
		ConnectionFactory factory = new ConnectionFactory();

		//2.设置连接所需信息
		factory.setHost("10.19.206.92");
		factory.setPort(5672);
		factory.setUsername("admin1");
		factory.setPassword("2015");
		factory.setVirtualHost("/");

		//3.创建连接
		Connection connection = factory.newConnection();

		//4.获取频道Channel
		Channel channel = connection.createChannel();

		//5.指定一个队列
		channel.queueDeclare(QUEUE_NAME,false,false,false,null);

		//6.发送的消息
		String message = "This is a confirm message!";

		//7.
		channel.confirmSelect();
		final long start = System.currentTimeMillis();

		//8.发送持久化消息
		for (int i = 0; i < 5; i++) {
			//第一个参数是exchangeName(默认情况下代理服务器端是存在一个""名字的exchange的,
			//因此如果不创建exchange的话我们可以直接将该参数设置成"",如果创建了exchange的话
			//我们需要将该参数设置成创建的exchange的名字),第二个参数是路由键
			channel.basicPublish("", QUEUE_NAME, MessageProperties.PERSISTENT_BASIC, (" Confirm模式， 第" + (i + 1) + "条消息").getBytes());
			if (channel.waitForConfirms()) {
				System.out.println("发送成功");
			}else{
				// 进行消息重发
			}
		}
		System.out.println("执行waitForConfirms耗费时间: " + (System.currentTimeMillis() - start) + "ms");
		// 9.关闭频道和连接
		channel.close();
		connection.close();

	}
}
